package com.thinkgem.jeesite.modules.sys.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by zhuo.shi on 2016/6/12.
 */
public class NumberGenerator {

    private static AtomicInteger seq = new AtomicInteger(0);    //目前只从内存中初始化，服务器重启会重新从0生成，如有需要可以从redis中取。

    /**
     * 获取唯一订单号，同一分钟内，支持最大订单为1w个
     * @return  订单号
     */
    public static String getNextStreamNo(){
        seq.compareAndSet(10000, 0);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String orderNo =  sdf.format(new Date());
        int seqNo = seq.getAndAdd(1);
        if (seqNo < 10){
            orderNo += "000" + seqNo;
        }else if (seqNo < 100){
            orderNo += "00" + seqNo;
        }else if (seqNo < 1000){
            orderNo += "0" + seqNo;
        }else {
            orderNo += String.valueOf(seqNo);
        }
        return orderNo;
    }

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(10001);
        for (int i =0; i < 10001; i++){
            Thread thread = new Thread(new Runnable(){
                @Override
                public void run() {
                    System.out.println(getNextStreamNo());
                }
            });
            thread.start();
            countDownLatch.countDown();
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
